﻿//Ext.ux.LoginMenu by Jose Alfonso Dacosta (galdaka - www.galdaka.es)

Ext.namespace("Ext.ux.Domino");

Ext.ux.Domino.LoginMenu = function(config){

	Ext.apply(this, config);
	
	this.userWindow = null;
		
	var clsId;
	Ext.util.CSS.createStyleSheet('.domino-menu-connect-icon' + '{background: url(' + this.menuConnectIconPath + ')}', clsId);
	Ext.util.CSS.createStyleSheet('.domino-menu-disconnect-icon' + '{background: url(' + this.menuDisconnectIconPath + ')}', clsId);
		
	this.items = [{
		id: 'domino-menu-connect',		  
    	text: this.menuConnectText,
     	iconCls: 'domino-menu-connect-icon',
     	handler: function(){
        	this.showLoginWindow();
		}.createDelegate(this)
	},{
		id: 'domino-menu-disconnect',		
    	text: this.menuDisconnectText,
		iconCls: 'domino-menu-disconnect-icon',
		handler: function(){
       		this.disconnect();
		}.createDelegate(this)
	}]
	
	this.menu = new Ext.menu.Menu({
		items: this.items,
		listeners: {
			beforeshow : function(){
				if(this.isConnected()){
					Ext.getCmp('domino-menu-connect').setVisible(false);
					Ext.getCmp('domino-menu-disconnect').setVisible(true);
				}else{
					Ext.getCmp('domino-menu-connect').setVisible(true);
					Ext.getCmp('domino-menu-disconnect').setVisible(false);
				}
			}.createDelegate(this)
		}
	});
	
	return this.menu; 
};

Ext.ux.Domino.LoginMenu.prototype = {

	showRegisterTab: true,
	
	windowLoginHeadImg: 'http://company/desarrollo/ext/ext2.nsf/extjs/ux/domino/loginmenu/login-big.gif',
	windowRegisterHeadImg: 'http://company/desarrollo/ext/ext2.nsf/extjs/ux/domino/loginmenu/register-big.gif',
	menuConnectIconPath: 'http://company/desarrollo/ext/ext2.nsf/extjs/ux/domino/loginmenu/connect-small.gif',
	menuDisconnectIconPath: 'http://company/desarrollo/ext/ext2.nsf/extjs/ux/domino/loginmenu/disconnect-small.gif',
	windowIconPath: 'http://company/desarrollo/ext/ext2.nsf/extjs/ux/domino/loginmenu/window-icon.gif',
	
	windowLoginHeadHtml: '<br><p style="padding-left: 10px;"><b>Introduzca usuario y password.</b></p>',
	windowRegisterHeadHtml: '<br><p style="padding-left: 10px;"><b>Introduzca los datos del nuevo usuario.</b></p>',
	errorMsgBodyGeneral: 'Se ha producido un error al intentar autenticarse. Pongase en contacto con el administrador (Error: ',
	windowLoginTabTitle: 'Login',
	windowRegisterTabTitle: 'Nuevo usuario',
	windowTitle: 'Autenticación de usuario',
	windowLoginUserText: 'Usuario',
	windowLoginPassText: 'Password',
	windowRegisterNameText: 'Nombre',
	windowRegisterSurnameText: 'Apellidos',
	windowRegisterUserText: 'Usuario',
	windowRegisterPassText: 'Password',
	loginErrorMsgTitle: 'Error al logearse',
	loginErrorMsgBody: 'Usuario y/o password incorrectos.',
	registerErrorMsgTitle: 'Error al registrarse',
	confirmDisconnectTitle: 'Cerrar sesión',
	confirmDisconnectMsg: '¿Está seguro que desea cerrar la sesión?',
	confirmRegisterTitle: 'Registro de usuario',
	confirmRegisterMsg: 'El nuevo usuario se dará de alta en la libreta de direcciones del servidor, y se añadirá a la LCA en esta aplicación. ¿Está seguro que desea continuar?',
	OKButtonText: 'Aceptar',
	menuConnectText: 'Iniciar sesión',
	menuDisconnectText: 'Cerrar sesión',
	
	loginUserNameText: 'El usuario debe ser un texto alfanumerico de 5 a 16 caracteres',
	loginPasswordText: 'El password debe ser un texto alfanumerico de 5 a 16 caracteres',
	registerNameText: 'El nombre del nuevo usuario debe ser un texto alfanumerico de 2 a 20 caracteres',
	registerSurNameText: 'Los apellidos del nuevo usuario deben ser un texto alfanumerico de 2 a 50 caracteres',	
	
	init: function(){
		
		Ext.QuickTips.init();
		Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
		
		var clsId;	
		Ext.util.CSS.createStyleSheet('.domino-user-login-head' + '{background: transparent}', clsId);
		Ext.util.CSS.createStyleSheet('.domino-user-login-window-icon' + '{background: url(' + this.windowIconPath + ')}', clsId);
	
		var logoPanel = new Ext.Panel({
			baseCls: 'x-plain',
			cls: 'domino-user-login-head',
			id: 'domino-login-head-panel',
			html: this.windowLoginHeadHtml,
			height: 50,
	   	    region: 'north'
		});
				
		var formPanel = new Ext.FormPanel({
			id: 'domino-user-form',
			labelWidth: 75,
		   	border:false,
		    width: 250,
			region: 'center',
			items: {
    	    	xtype:'tabpanel',
				id: 'domino-login-tabPanel',
		        activeTab: 0,
				bodyborder: false,
				border: false,
        	    defaults:{autoHeight:true, bodyStyle:'padding:10px; padding-top:20px'}, 
		        items:[{
        	       	title: this.windowLoginTabTitle,
		       	   	layout:'form',
					id: 'domino-login-tab',
    	            defaults: {width: 230},
        			defaultType: 'textfield',
		            items: [{
        	    	    fieldLabel: this.windowLoginUserText,
						id: 'domino-login-userName',
						vtype: 'loginUserName',
		               	allowBlank:false,
						listeners: {
							invalid: function(){
								Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							valid: function(){
								Ext.getCmp('domino-login-password').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							specialkey: function(f, e){
								if(e.getKey() == 13 && Ext.getCmp('domino-login-userName').isValid() && Ext.getCmp('domino-login-password').isValid() && Ext.getCmp('domino-submit-button').disabled == false){
									Ext.getCmp('domino-submit-button').handler.call(Ext.getCmp('domino-submit-button').scope)
								}
							}
						}
               		 },{
		            	 fieldLabel: this.windowLoginPassText,
						 id: 'domino-login-password',
						 vtype: 'loginPassword',
				 	     inputType: 'password',
  		           	     allowBlank:false,
 						 listeners: {
						 	invalid: function(){
								Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							valid: function(){
								Ext.getCmp('domino-login-userName').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							specialkey: function(f, e){
								if(e.getKey() == 13 && Ext.getCmp('domino-login-userName').isValid() && Ext.getCmp('domino-login-password').isValid() && Ext.getCmp('domino-submit-button').disabled == false){
									Ext.getCmp('domino-submit-button').handler.call(Ext.getCmp('domino-submit-button').scope)
								}
							}
					 	 }
					 }]
				},{
               		title: this.windowRegisterTabTitle,
		            layout:'form',
					id: 'domino-register-tab',
        			defaults: {width: 230},
                	defaultType: 'textfield',
		            items: [{
						id: 'domino-newuser-name',
 		       			fieldLabel: this.windowRegisterNameText,
						vtype: 'registerName',
  		    	        allowBlank:false,
						listeners: {
						 	invalid: function(){
								Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							valid: function(){
								Ext.getCmp('domino-newuser-surname').isValid() && Ext.getCmp('domino-newuser-username').isValid() && Ext.getCmp('domino-newuser-password').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
							}
						}
        			},{
						id: 'domino-newuser-surname',
        		    	fieldLabel: this.windowRegisterSurnameText,
						vtype: 'registerSurName',
  		                allowBlank:false,
						listeners: {
						 	invalid: function(){
								Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							valid: function(){
								Ext.getCmp('domino-newuser-name').isValid() && Ext.getCmp('domino-newuser-username').isValid() && Ext.getCmp('domino-newuser-password').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
							}
						}
		           	},{
						id: 'domino-newuser-username',
        		 	    fieldLabel: this.windowRegisterUserText,
						vtype: 'loginUserName',
	  		            allowBlank:false,
						listeners: {
						 	invalid: function(){
								Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							valid: function(){
								Ext.getCmp('domino-newuser-surname').isValid() && Ext.getCmp('domino-newuser-name').isValid() && Ext.getCmp('domino-newuser-password').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
							}
						}
					},{
						id: 'domino-newuser-password',
        				fieldLabel: this.windowRegisterPassText,
					    inputType: 'password',
						vtype: 'loginPassword',
  		            	allowBlank:false,
						listeners: {
						 	invalid: function(){
								Ext.getCmp('domino-submit-button').setDisabled(true);
							},
							valid: function(){
								Ext.getCmp('domino-newuser-surname').isValid() && Ext.getCmp('domino-newuser-username').isValid() && Ext.getCmp('domino-newuser-name').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
							}
						}
		            }]
				}],
				listeners: {
					tabchange: function(tp, p){
						switch(tp.activeTab.id){
							case 'domino-login-tab':
								Ext.getCmp('domino-login-window').setHeight(230);
								Ext.getCmp('domino-login-head-panel').body.update(this.windowLoginHeadHtml);
								Ext.util.CSS.updateRule('.domino-user-login-head', 'background', 'transparent url(' + this.windowLoginHeadImg + ') no-repeat right !important');
								Ext.getCmp('domino-login-userName').isValid() && Ext.getCmp('domino-login-password').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
								break;
							case 'domino-register-tab':
								Ext.getCmp('domino-login-window').setHeight(280);
								Ext.getCmp('domino-login-head-panel').body.update(this.windowRegisterHeadHtml);
								Ext.util.CSS.updateRule('.domino-user-login-head', 'background', 'transparent url(' + this.windowRegisterHeadImg + ') no-repeat right !important');
								Ext.getCmp('domino-newuser-name').isValid() && Ext.getCmp('domino-newuser-surname').isValid() && Ext.getCmp('domino-newuser-username').isValid() && Ext.getCmp('domino-newuser-password').isValid() ? Ext.getCmp('domino-submit-button').setDisabled(false) : Ext.getCmp('domino-submit-button').setDisabled(true);
								break;
						}
					}.createDelegate(this)
				}
		    }
		});
			
		this.userWindow = new Ext.Window({
			id: 'domino-login-window',
			title: this.windowTitle,
		    layout: 'border',
			modal: true,
            width: 350,
	        closeAction:'hide',
    	    plain: true,
			iconCls: 'domino-user-login-window-icon',
            buttons:[{
				id: 'domino-submit-button',
                text: this.OKButtonText,
               	handler: function(){
					Ext.getCmp('domino-submit-button').setDisabled(true);
					switch (Ext.getCmp('domino-login-tabPanel').activeTab.id){
						case 'domino-register-tab':
							this.register();
							break;
						case 'domino-login-tab':	
							this.connect();
							this.setBackupUserSessionID();
							Ext.getCmp('domino-user-form').getForm().reset();
							break;
					}
                }.createDelegate(this)
			}],	
			items: [logoPanel, formPanel],
			buttonAlign: 'center',
			draggable: false,
			plain: false,
		    resizable: false
		});
	},
			
	showLoginWindow: function(){
		if (!this.userWindow){
  	   	 	this.init();
		}
		this.userWindow.show();
		if(!this.showRegisterTab){Ext.getCmp('domino-login-tabPanel').hideTabStripItem(Ext.getCmp('domino-register-tab'))};
		Ext.getCmp('domino-user-form').getForm().reset();
		Ext.getCmp('domino-submit-button').setDisabled(true);
		Ext.getCmp('domino-login-tabPanel').setActiveTab(Ext.getCmp('domino-login-tab'));		
		Ext.getCmp('domino-login-userName').focus();
	},
		
	disconnect: function(){	
		Ext.Msg.confirm(
			this.confirmDisconnectTitle,
			this.confirmDisconnectMsg,
			function(o){
				if(o == 'yes'){
					if(this.isConnected()){
						Ext.Ajax.request({
							url: '/names.nsf?logout',
							scope: this,
							success: function(o){
								document.cookie = "BackupSesID=; expires=Thu, 01-Jan-70 00:00:01 GMT";
								window.location.reload();
							},
							failure: function(){this.failure(this.errorMsgTitle7, 'Cod.7')}
						})
					}else{
						this.failure(this.errorMsgTitle6, 'Cod.6');
					}
				}
			}.createDelegate(this)
		)
	},

	register: function(){
		Ext.Msg.confirm(
			this.confirmRegisterTitle,
			this.confirmRegisterMsg,
			function(o){
				if(o == 'yes'){
					Ext.Ajax.request({
						url: 'Ext.ux.Domino.RegisterWebUser?OpenAgent',
						scope: this,
						success: function(o){
							Ext.getCmp('domino-user-form').getForm().reset();
							this.failure(this.registerErrorMsgTitle, 'Cod.12', o.responseXML.text);
						},
		    			failure: function(){this.failure(this.registerErrorMsgTitle, 'Cod.11')},
						params: {n: Ext.get('domino-newuser-name').dom.value, s: Ext.get('domino-newuser-surname').dom.value, u: Ext.get('domino-newuser-username').dom.value, p: Ext.get('domino-newuser-password').dom.value}
					});	
				}
			}.createDelegate(this)
		)
	},
	
	connect: function(){
		Ext.Ajax.request({
			url: '/names.nsf?login',
			scope: this,
			success: function(o1){
				if (o1.responseText.indexOf('reasonType')==-1){
					Ext.Ajax.request({
						url: window.location.href.toLowerCase().split('.nsf')[0] + '.nsf?OpenDatabase',
						scope: this,
						success: function(o2){
							if (o2.responseText.indexOf('reasonType')==-1){
								document.cookie = "BackupSesID=; expires=Thu, 01-Jan-70 00:00:01 GMT";
								window.location.reload();
							}else{
								Ext.Ajax.request({
									url: '/names.nsf?logout',
									scope: this,
									success: function(o3){
										if(document.cookie.indexOf('BackupSesID=')!= -1){
											document.cookie = "DomAuthSessId=" + document.cookie.split('BackupSesID=')[1].substr(0, 32);
										}
										document.cookie = "BackupSesID=; expires=Thu, 01-Jan-70 00:00:01 GMT";
										this.failure(this.loginErrorMsgTitle, 'Cod.5');
									},
									failure: function(){this.failure(this.loginErrorMsgTitle, 'Cod.4')}
								})
							}
						},
						failure: function(){this.failure(this.loginErrorMsgTitle, 'Cod.3')}
					})										
				}else{
					this.failure(this.loginErrorMsgTitle, 'Cod.2', this.loginErrorMsgBody);
				}	
			},
			failure: function(){this.failure(this.loginErrorMsgTitle, 'Cod.1')},
			params: {UserName: Ext.get('domino-login-userName').dom.value, Password: Ext.get('domino-login-password').dom.value}
		});
	},
	
	failure: function(title, errorType, msg){
		Ext.MessageBox.show({
			title: title || 'Error',
			msg: msg || this.errorMsgBodyGeneral + errorType + ').' ,
			buttons: Ext.MessageBox.OK,
			buttonText: this.OKButtonText,
			icon: Ext.MessageBox.ERROR
		});
	},
	
	setBackupUserSessionID: function(){
		if(document.cookie.indexOf('DomAuthSessId=')!=-1){
			document.cookie = "BackupSesID=" + document.cookie.split('DomAuthSessId=')[1].substr(0, 32);
		}
	},
	
	isConnected: function(){
		if(document.cookie.indexOf('DomAuthSessId=')!= -1){
			var sessionIDs = document.cookie.split('DomAuthSessId=');
			var sessionID = sessionIDs[sessionIDs.length - 1].substr(0, 32);
			if (/^[0-9A-Z]{32}$/.test(sessionID)){
				return true;
			}
		}
		return false;
	}
	
};

//DEFINE VTYPES
if (Ext.ux.Domino.LoginMenu){
	Ext.apply(Ext.form.VTypes,{	
			  
  	 	loginUserNameText: Ext.ux.Domino.LoginMenu.prototype.loginUserNameText,	
		loginUserNameMask: /[a-z0-9_ ]/,
		loginUserNameVal: /^[a-zA-Z0-9_ ]{5,16}$/,
		loginUserName: function(v){
			return this.loginUserNameVal.test(v);
		},
			
		loginPasswordText: Ext.ux.Domino.LoginMenu.prototype.loginUserNameText,
		loginPasswordMask: /[a-zA-Z0-9]/,
		loginPasswordVal: /^[a-zA-Z0-9_ ]{5,16}$/,
		loginPassword: function(v){
			return this.loginPasswordVal.test(v);
		},
	
		registerNameText: Ext.ux.Domino.LoginMenu.prototype.registerNameText,
		registerNameMask: /[a-zA-Z0-9 ]/,
		registerNameVal: /^[a-zA-Z0-9_ ]{2,20}$/,
		registerName: function(v){
			return this.registerNameVal.test(v);
		},
	
		registerSurNameText: Ext.ux.Domino.LoginMenu.prototype.registerSurNameText,
		registerSurNameMask: /[a-zA-Z0-9 ]/,
		registerSurNameVal: /^[a-zA-Z0-9_ ]{2,50}$/,
		registerSurName: function(v){
			return this.registerSurNameVal.test(v);
		}
			
	});
}